package com.antd.common.log.util;

import com.antd.common.log.annotation.SystemLog;
import com.google.common.collect.Maps;
import lombok.experimental.UtilityClass;
import org.aspectj.lang.JoinPoint;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/11/19 10:43
 */
@UtilityClass
public class LogUtil {
    public Map<String,String> getControllerMethod(JoinPoint point) throws Exception {
        Map<String,String> param= Maps.newHashMap();
        // 获取连接点目标类名
        String targetName = point.getTarget().getClass().getName();
        // 获取连接点签名的方法名
        String methodName = point.getSignature().getName();
        //获取连接点参数
        Object[] args = point.getArgs();
        //根据连接点类的名字获取指定类
        Class targetClass = Class.forName(targetName);
        //获取类里面的方法
        Method[] methods = targetClass.getMethods();
        String description = "";
        String methodType="";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == args.length) {
                    description = method.getAnnotation(SystemLog.class).description();
                    methodType=method.getAnnotation(SystemLog.class).type().name();
                    param.put("description",description);
                    param.put("methodType",methodType);
                    break;
                }
            }
        }
        return param;
    }
    /**
     * 获取堆栈信息
     *
     * @param throwable
     * @return
     */
    public String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }
}
